//
//  CommentController.swift
//  OnceNectar
//
//  Created by Zhang Dream on 2018/7/18.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class CommentController: BaseViewController, UITableViewDelegate, UITableViewDataSource, BottomShadow, XHInputViewDelagete, ConsultaionCommentTableViewCellDelegate, AddCornerUIRectCorner {

    @IBOutlet weak var mainTable: UITableView!
    @IBOutlet weak var bottomView: UIView!
    var commentData:[myCommendModel] = []
    
    var headerImage: UIImageView?
    var nameLable:UILabel?
    var levelLable: UILabel?
    var dateLable: UILabel?
    var contentLable: UILabel?
    var model: myCommendModel?
 
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    var page:Int = 0
    var totalPage:Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.lightGray
        // Do any additional setup after loading the view.
        setUpUI()
//        setShadow(view: mainTable, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        setShadow(view: bottomView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
//        addCornerWithView(aView: mainTable, aCorners: [.topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
    }

    func setUpUI() -> Void {
        
        self.title = "评论详情"
        mainTable.register(UINib(nibName: "ConsultaionCommentTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        mainTable.estimatedRowHeight = 100
        mainTable.rowHeight = UITableViewAutomaticDimension
        mainTable.backgroundColor = UIColor.clear
        
        let headerView: UIView? = UIView()
       
        headerView?.backgroundColor = UIColor.white
        headerView?.frame = CGRect(x: 0, y: 0, width: ScreenWidth - 16, height: 180)
        let headerImage = UIImageView()
        headerImage.left = 10
        headerImage.top = 10
        headerImage.width = 30
        headerImage.height = 30
        headerImage.layer.masksToBounds = true
        headerImage.layer.cornerRadius = 15
        headerView?.addSubview(headerImage)
        self.headerImage = headerImage
        
        let name = UILabel()
        name.left = headerImage.right + 15
        name.top = headerImage.top + 10
        name.text = ""
        name.textColor = UIColor.blue
        name.font = UIFont.systemFont(ofSize: 12)
        name.sizeToFit()
        headerView?.addSubview(name)
        nameLable = name
        
        let level = UILabel()
        level.left = name.right + 25
        level.top = name.top + 3
        level.text = ""
        level.textColor = UIColor.gray
        level.font = UIFont.systemFont(ofSize: 10)
        level.sizeToFit()
        headerView?.addSubview(level)
        levelLable = level
        
        let date = UILabel()
        date.left = name.left
        date.top = name.bottom + 3
        date.text = ""
        date.textColor = UIColor.gray
        date.font = UIFont.systemFont(ofSize: 10)
        date.sizeToFit()
        headerView?.addSubview(date)
        dateLable = date
        
        let content = UILabel()
        content.left = name.left + 20
        content.width = ScreenWidth - 16 - 80
        content.top = date.bottom + 8
        content.height = 0
        content.text = ""
        content.textAlignment = .left
        content.numberOfLines = 0
        content.lineBreakMode = .byWordWrapping
        content.textColor = UIColor.darkGray
        content.font = UIFont.systemFont(ofSize: 10)
        headerView?.addSubview(content)
        contentLable = content
        
        self.bottomView.addSubview(setButtomView())
        
        let huifu = UILabel()
        huifu.left = 10
        huifu.text = "回复"
        huifu.textColor = UIColor.darkGray
        huifu.font = UIFont.systemFont(ofSize: 15)
        huifu.sizeToFit()
        huifu.bottom = (headerView?.bottom)! - 2
        headerView?.addSubview(huifu)
        
//        setShadow(view: headerView!, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        addCornerWithView(aView: headerView!, aCorners: [.topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        headerView?.autoresizingMask = .init(rawValue: 0)
        self.mainTable.tableHeaderView = headerView
        
        self.navigationItem.rightBarButtonItem = nil
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        mainTable.mj_header = header
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        mainTable.reloadData()
        
        headerRefresh()
        self.mainTable.reloadData()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return commentData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ConsultaionCommentTableViewCell
        cell.delegate = self
        cell.reportType = "article"
        cell.tag = indexPath.row
        cell.contentView.backgroundColor = UIColor.white
        cell.setData(datas: commentData[indexPath.row])
        //        switch consultationDetailType {
        //        case .news:
        //            cell.setData(datas: model!.comments[indexPath.row])
        ////        case .video:
        //////            cell.setData(datas: videoModel!.comments[indexPath.row])
        ////        case .use:
        ////            cell.setData(datas: videoModel!.comments[indexPath.row])
        //        }
        return cell
    }
    
    func like(model: myCommendModel,tag:Int){
        
        commentLike(parameters: ["commentator":(MineInfoModel.share.userInfModel?.nickname!)!,"commentatorID":(MineInfoModel.share.userInfModel?.id!)!,
                                 "commentId":model.id!,"source":"article"],cellModel: model,tag:tag)
    }
    ///MARK: - ConsultaionCommentTableViewCellDelegate
    func reloadSuperTable(_ cell: ConsultaionCommentTableViewCell) {
        let indexPath = mainTable.indexPath(for: cell)
        mainTable.reloadData()
    }
    
    /// 点赞
    func commentLike(parameters: [String:Any],cellModel:myCommendModel,tag:Int) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(commentLikeUrl)"
        
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    self.showToast(msg:json["message"].string!)
                                }
                            }else{
                                self.showToast(msg:String(describing: response.error))
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    /// 设置底部视图
    private func setButtomView() -> UIView {
        let superSidMargin: CGFloat = 10
        let bottomHeight: CGFloat = 48
        let bottomView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth - 16, height: bottomHeight))
        bottomView.backgroundColor = ONColor.cellBGColor
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: bottomView.width, height: bottomHeight))
        bgView.backgroundColor = ONColor.inputBoxBGColor
        bottomView.addSubview(bgView)
        addCornerWithView(aView: bgView, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        //        setShadow(view: bgView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        let sideMargin: CGFloat = 8
        let tbMargin: CGFloat = 5
        
        let btn = UIButton(type: .custom)
        btn.setTitle("我也要说两句……", for: .normal)
        btn.backgroundColor = UIColor.white
        btn.contentHorizontalAlignment = .left
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)
        btn.frame = CGRect(x: sideMargin, y: tbMargin, width: bgView.width - sideMargin * 2, height: bgView.height - tbMargin * 2)
        btn.setTitleColor(ONColor.placeholderTextColor, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btn.layer.cornerRadius = btn.height / 2
        btn.addTarget(self, action: #selector(inptBoxTap), for: .touchUpInside)
        bgView.addSubview(btn)
        return bottomView
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新") // 结束刷新
        page = 0
        footerRefresh()
    }
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        fetchCommentList(parameters: ["page":page,"pageSize":10, "commentId":(model?.id)!])
    }
    
    /// MARK: - 设置弹出键盘
    @objc func inptBoxTap() {
        if !MineInfoModel.share.isLogin {
            let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
            self.navigationController?.pushViewController(loginVC, animated: true)
            return
        }
        XHInputView.show(with: .large, configurationBlock: { inputView in
            inputView?.delegate = self
            inputView?.placeholder = "请输入评论文字..."
            inputView?.maxCount = 50
            inputView?.textViewBackgroundColor = UIColor.groupTableViewBackground
        }) { (str) -> Bool in
            if let text = str {
                if !text.isEmpty {
                    self.sendComment(parameters: ["replyContent":text,"replyCommentId":(self.model?.id)!])
                    HUD.show(.label("加载中..."))
                    return true
                }
                return false
            }
            return false
        }
    }
    
    /// 发表评论
    func sendComment(parameters: [String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(replyCommentUrl)"
        
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:"发送成功")
                                        DispatchQueue.main.async{
                                            self.headerRefresh()
                                        }
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                        
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"发送失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 获取评论内容
    func fetchCommentList(parameters: [String:Any]) -> Void {
        let requesturl = appendUrl(suffix: relateCommentListUrl)
        
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                  
                                            if self.page == 1{
                                                self.commentData.removeAll()
                                                self.mainTable.mj_header.endRefreshing()
                                            }
                                            else{
                                                self.mainTable.mj_footer.endRefreshing()
                                            }
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            var model = myCommendModel(fromDic: dic)
                                            
                                            let relatedComments = dic["relatedComments"]?.array!
                                            
                                            if let dict = dic["beRepliedUser"]?.dictionary {
                                                model.initReplied(dic: dict)
                                            }
                                            
                                            model.initRelatedComments(arr: relatedComments!)
                                            
                                            let author = dic["commentUser"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthor(dic: (author?.dictionary!)!)
                                            }
                                            self.commentData.append(model)
                                        }
                                        if self.totalPage == self.commentData.count{
                                            self.mainTable.mj_footer=nil
                                        }
                                        else{
                                            self.mainTable.mj_footer = self.footer
                                        }
                                        self.headerImage?.sd_setImage(with: appendUrl(suffix: (self.model?.commentUser?.headIcon)!), completed: nil)
                                        self.nameLable?.text = self.model?.commentUser?.nickname
                                        self.levelLable?.snp.updateConstraints { (make) in
                                            make.left.equalTo((self.nameLable?.snp.right)!).offset(10)
                                            make.centerY.equalTo((self.nameLable?.snp.centerY)!)
                                        }
                                        self.levelLable?.text = self.model?.commentUser?.grade?.gradeCode
                                        self.dateLable?.snp.updateConstraints { (make) in
                                            make.left.equalTo((self.levelLable?.snp.right)!).offset(10)
                                            make.centerY.equalTo((self.nameLable?.snp.centerY)!)
                                        }
                                        self.dateLable?.text = self.model?.created
                                        self.contentLable?.snp.updateConstraints { (make) in
                                            make.top.equalTo((self.nameLable?.snp.bottom)!).offset(10)
                                            make.left.equalTo((self.nameLable?.snp.left)!).offset(0)
                                        }
                                        self.contentLable?.text = self.model?.commentContent
                                        
                                        self.nameLable?.sizeToFit()
                                        self.levelLable?.sizeToFit()
                                        self.dateLable?.sizeToFit()
                                        self.contentLable?.sizeToFit()
                                        self.mainTable.reloadData()
                                        
                                    }
                                    else{
                                        if self.page == 1{
                                            self.mainTable.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTable.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.mainTable.mj_header.endRefreshing()
                                }
                                else{
                                    self.mainTable.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
        
    func xhInputViewWillShow(_ inputView: XHInputView!) {
        IQKeyboardManager.shared.enable = false;
    }
        
    func moreAct(model: myCommendModel) {
        let comm = CommentController()
        comm.model = model
        self.navigationController?.pushViewController(comm, animated: true)
    }
        
    func xhInputViewWillHide(_ inputView: XHInputView!) {
        IQKeyboardManager.shared.enable = true
    }
    func jb(model:myCommendModel,reportType:String) -> Void {
        let report = ReportView()
        report.show(contnets: ["发布不正当内容对我造成骚扰", "存在欺诈骗钱行为", "此账号可能被盗用", "发布仿冒信息"], type: .report) { (index, view) in
            
            let content:String = report.titles[index]
            let parameter:[String : String] = ["source": reportType,"reportContent":content,"jointId":model.id!]
            //                var headparams:NSMutableDictionary = NSMutableDictionary()
            //                headparams["Content-Type"] =
            
            let head: HTTPHeaders = ["Content-Type":"application/json;charset=UTF-8","token":MineInfoModel.share.token!]
            Alamofire.request(appendUrl(suffix: reportUrl), method: .post,
                              parameters: parameter,
                              encoding: URLEncoding.httpBody,
                              headers: head).responseJSON {
                                (response) in
                                
                                if(response.error == nil){
                                    if let result = response.result.value as? NSDictionary
                                    {
                                        
                                        let json = JSON(result)
                                        if json["code"].int == 1{
                                            self.showToast(msg:"举报成功")
                                            report.hide()
                                        }
                                        else{
                                            self.showToast(msg:"举报失败")
                                            report.hide()
                                        }
                                    }
                                }else{
                                    self.showToast(msg:"举报失败")
                                    report.hide()
                                }
                                
            }
        }
    }
}
